<template>
    <div ref="threeContainer" class="three-container"></div>
  </template>
  
  <script>
  import * as THREE from 'three';
  import { onMounted, ref } from 'vue';
  import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
  
  export default {
    name: 'ThreeScene',
    setup() {
      const threeContainer = ref(null);
  
      onMounted(() => {
        initThree();
      });
  
      const initThree = () => {
        // 创建场景
        const scene = new THREE.Scene();
  
        // 创建相机
        const camera = new THREE.PerspectiveCamera(75, threeContainer.value.clientWidth / threeContainer.value.clientHeight, 0.1, 1000);
        camera.position.z = 5;
  
        // 创建渲染器
        const renderer = new THREE.WebGLRenderer();
        renderer.setSize(threeContainer.value.clientWidth, threeContainer.value.clientHeight);
        threeContainer.value.appendChild(renderer.domElement);
  
        // 创建几何体和材质
        // const geometry = new THREE.BoxGeometry();
        const geometry = new THREE.SphereGeometry();

        const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
        const cube = new THREE.Mesh(geometry, material);
        // cube.position.set(0,10,0);
        scene.add(cube);
  
        // 添加光源
        const light = new THREE.DirectionalLight(0xffffff, 1);
        light.position.set(1, 1, 1).normalize();
        scene.add(light);
  
        // 添加 OrbitControls
        const controls = new OrbitControls(camera, renderer.domElement);
        controls.update();
  
        // 渲染循环
        const animate = function () {
          requestAnimationFrame(animate);
  
          // 旋转立方体
          cube.rotation.x += 0.01;
          cube.rotation.y += 0.01;
  
          controls.update();
          renderer.render(scene, camera);
        };
  
        animate();
  
        // 监听窗口大小变化
        window.addEventListener('resize', () => {
          camera.aspect = threeContainer.value.clientWidth / threeContainer.value.clientHeight;
          camera.updateProjectionMatrix();
          renderer.setSize(threeContainer.value.clientWidth, threeContainer.value.clientHeight);
        });
      };
  
      return {
        threeContainer,
      };
    },
  };
  </script>
  
  <style scoped>
  .three-container {
    width: 100% !important;
    height: 100% !important;
    /* width: 500px;
    height: 500px;*/
  } 
  </style>